import requests


class Anticrawler(object):
    """docstring for ClassName"""

    def __init__(self, _session):
        super(Anticrawler, self).__init__()
        self.session = _session

    # auto cookies update function
    def auto_cookie_update(self, _response):

        # set cookies
        def setcookie(_headers):
            return {i.split(";")[0].split("=")[0].strip(): i.split(";")[0].split("=")[1].strip() for i in _headers.get("Set-Cookie").split(",")}

        # cookie to dict
        def ctd(_cookies):
            return requests.utils.dict_from_cookiejar(_cookies)

        # dict to cookie
        def dtc(_dicts):
            return requests.utils.cookiejar_from_dict(_dicts)

        # dict update
        def dup(_dicts, _adds):
            _dicts.update(_adds)
            return _dicts
        try:
            self.session.cookie = dtc(
                dup(ctd(self.session.cookies), setcookie(_response.headers)))
        except Exception as e:
            print("| [Autocookie] :", e)

    def random_user_agent(self):
        UserAgentList = [
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1",
            "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; InfoPath.2; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; 360SE)",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
            "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
            "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; Tablet PC 2.0; .NET4.0E)",
            "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)",
            "Mozilla/5.0 (X11; U; Linux i686; rv:1.7.3) Gecko/20040913 Firefox/0.10",
            "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; ja) Presto/2.10.289 Version/12.00",
            "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36"
        ]
        self.session.headers.update({"User-Agent": random.choice(ulist)})
